package com.pap.rbac.resource.agent.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.pap.base.service.impl.PapBaseServiceImpl;
import com.pap.base.util.date.DateUtils;
import com.pap.base.util.string.StringUtilss;
import com.pap.obj.vo.response.ResponseVO;
import com.pap.rbac.agent.resource.IResourceAgent;
import com.pap.rbac.agent.resource.dto.ResourceTreeNodeVO;
import com.pap.rbac.resource.auto.entity.Resource;
import com.pap.rbac.resource.auto.mapper.ResourceMapper;

@Transactional
@Service("resourceAgent")
public class ResourceAgentImpl extends PapBaseServiceImpl<Resource> implements IResourceAgent {

	@Autowired
	private ResourceMapper resourceMapper;
	

	@Override
	public List<ResourceTreeNodeVO> resourceTreeJson(String clientLicenseId, String globalParentId) {
		return resourceMapper.resourceTreeJson(clientLicenseId, globalParentId);
	}

	@Override
	public ResponseVO<Resource> updateAndCheckResource(Resource inputResource, String loginUserId) {
		// 检验是否循环依赖
		if(checkTreeCircularDependency(inputResource.getId(), inputResource.getParentId())) {
			// 更新当前的资源菜单
			inputResource.setModifyIp("0.0.0.0");
			inputResource.setModifyTime(DateUtils.getCurrDateTimeStr());
			inputResource.setModifyUser(loginUserId);
			
			resourceMapper.updateByPrimaryKeySelective(inputResource);
			
			if("-1".equals(inputResource.getParentId())) {
				Resource tempForPath = resourceMapper.selectByPrimaryKey(inputResource.getId());
				tempForPath.setPathCodes(null);
				tempForPath.setPathIds(null);
				tempForPath.setPathNames(null);
				tempForPath.setLevel("0");
				resourceMapper.updateByPrimaryKey(tempForPath);
			} else {
				Resource tempForPath = resourceMapper.selectByPrimaryKey(inputResource.getId());
				Resource tempParentForPath = resourceMapper.selectByPrimaryKey(inputResource.getParentId());
				if(StringUtilss.isNotEmpty(tempParentForPath.getPathIds())) {
					tempForPath.setPathIds(tempParentForPath.getPathIds() + "," + tempParentForPath.getId());
        		} else {
        			tempForPath.setPathIds(tempParentForPath.getId());
        		}
        		if(StringUtilss.isNotEmpty(tempParentForPath.getPathCodes())) {
        			tempForPath.setPathCodes(tempParentForPath.getPathCodes() + "," + tempParentForPath.getCode());
        		} else {
        			tempForPath.setPathCodes(tempParentForPath.getCode());
        		}
        		if(StringUtilss.isNotEmpty(tempParentForPath.getPathNames())) {
        			tempForPath.setPathNames(tempParentForPath.getPathNames() + "," + tempParentForPath.getName());
        		} else {
        			tempForPath.setPathNames(tempParentForPath.getName());
        		}
				// level
				if(StringUtilss.isNotEmpty(tempParentForPath.getLevel())) {
					tempForPath.setLevel((Integer.parseInt(tempParentForPath.getLevel()) + 1) + "");
				} else {
					tempForPath.setLevel("0");
				}
        		resourceMapper.updateByPrimaryKey(tempForPath);
			}
			
			// 维护子集的资源菜单
			ResponseVO<Resource> responseVO =  updateRecursionPathColumnResource(inputResource.getId());
			return responseVO;
		} else {
			return ResponseVO.validfail("资源菜单被循环依赖，请检查数据有效性!");
		}
	}
	
	/**
	 * 新维护的资源菜单，是否被循环依赖的校验
	 * @param operaResourceId
	 * @param newParentResourceId
	 * @return
	 */
	@Override
    public Boolean checkTreeCircularDependency(String operaResourceId, String newParentResourceId) {
    	String parentResourceTemp = "";
    	Resource newParentResourceInfo = resourceMapper.selectByPrimaryKey(newParentResourceId);
    	if(newParentResourceInfo != null) {
    		if(StringUtilss.isNotEmpty(newParentResourceInfo.getPathIds())) {
    			parentResourceTemp = newParentResourceInfo.getPathIds() + ",";
    		}
    		parentResourceTemp += newParentResourceInfo.getId();
    	}
    	if (StringUtilss.checkArrayValue(parentResourceTemp.split(","), operaResourceId)) {
    		return false;
    	} else {
    		return true;
    	}
    }

	@Override
	public ResponseVO<Resource> updateRecursionPathColumnResource(String inputResourceId) {
		try {  
			Map<Object, Object> parentIdMap = new HashMap<Object, Object>();
			parentIdMap.put("parentId", inputResourceId);
            List<Resource> list = resourceMapper.selectListByMap(parentIdMap);
            if (null != list && list.size()>0) {  
                for (int i = 0; i < list.size(); i++) {  
                	Resource resource = list.get(i);  
                	// 更新数据
                	Resource parentTemp = resourceMapper.selectByPrimaryKey(resource.getParentId());
                	if(parentTemp != null) {
                		if(StringUtilss.isNotEmpty(parentTemp.getPathIds())) {
                			resource.setPathIds(parentTemp.getPathIds() + "," + parentTemp.getId());
                		} else {
                			resource.setPathIds(parentTemp.getId());
                		}
                		if(StringUtilss.isNotEmpty(parentTemp.getPathCodes())) {
                			resource.setPathCodes(parentTemp.getPathCodes() + "," + parentTemp.getCode());
                		} else {
                			resource.setPathCodes(parentTemp.getCode());
                		}
                		if(StringUtilss.isNotEmpty(parentTemp.getPathNames())) {
                			resource.setPathNames(parentTemp.getPathNames() + "," + parentTemp.getName());
                		} else {
                			resource.setPathNames(parentTemp.getName());
                		}
        				// level
        				if(StringUtilss.isNotEmpty(parentTemp.getLevel())) {
        					resource.setLevel((Integer.parseInt(parentTemp.getLevel()) + 1) + "");
        				} else {
        					resource.setLevel("0");
        				}
                		
                	} else {
                		resource.setPathCodes(null);
                		resource.setPathIds(null);
                		resource.setPathNames(null);
                	}
                	resourceMapper.updateByPrimaryKey(resource);
                	updateRecursionPathColumnResource(resource.getId());  
                }  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
            return ResponseVO.validfail(e.getMessage());
        }  
		return ResponseVO.successdata("更新成功");
	}

	@Override
	public List<Resource> selectListByUserAndLicense(String userId, String clientLicenseId) {
		return resourceMapper.selectListByUserAndLicense(userId, clientLicenseId);
	}
}
